"""HiroSQL Interactive Interpreter - James Gardner"""
    
import sys, os.path
sys.path.append('../')
import HiroSQL
from PythonDriver.ClientDriver import Driver

sys.path.append(HiroSQL.__name__+'/external')
sys.path.append(HiroSQL.__name__+'/client')
sys.path.append(HiroSQL.__name__)
import code, traceback, time
from tablePrint import table as printtable

# Set up True and False
try:
    True
except NameError:
    True = (1==1)
    False = (1==0)
    
__version__ = HiroSQL.__version__

class SQLConsole(code.InteractiveConsole):
    "HiroSQL Interactive Interpreter Class"
    def __init__(self, database, catchErrors=True, header="HiroSQL Console", locals=None):
        code.InteractiveConsole.__init__(self, locals, header)
        self.database = database
        self.catchErrors = catchErrors

    def push(self, line):
        "If the line is a keyword, handle it. Otherwise send the line to the database as SQL."
        if line == 'help':
            print "No help yet available."
        elif line == 'copyright':
            print "Copyright Hiro Zhu 2011, All rights reserved. http://code.google.com/p/db-china/"
        elif line == 'license':
            print "Released under the GNU GPL available to read at http://code.google.com/p/db-china/"
        elif line == 'exit':
            sys.exit(0)
        else:
            while line and line[1:] == ' ':
                line = line[1:]
            while line and line[-1:] == ' ':
                line = line[:-1]
            if not line:
                pass
            else:
                try:
                    self.buffer.append(line)
                    more = self.execute(line)
                    source = "\n".join(self.buffer)
                    #more = self.runsource(source, self.filename)
                    #if not more:
                    self.resetbuffer()
                    return more
                except SystemExit:
                    raise
                except:
                    self.showtraceback()

    def execute(self, sql):
        """Connect to the database, execute the SQL, return the result then close the connection
        so other users can access it."""
        mydr = Driver('',7911,'root','123456',self.database)
        mydr.Connect()
        mydr.Open()

        res1=mydr.Execute(sql)
        mydr.Close();

        if res1.Status == 1:
			self.printNormalResult(res1)
        else:
			self.printErrorResult(res1)
			
    def printNormalResult(self, res):
		for table in res.Datas.Tables:
			cols = []
			t = table.UsedTime
			rows = table.AffectedNum
			
			colsObjects=[]
			for column in table.Columns:
				cols.append(column.Name)
				colsObjects.append(column)
			tablecontent=[]	
			for row in table.Rows:
				tmpList=[]
				for colData in colsObjects:					
					tmpList.append(row.ColumnDatas[colData])

				tablecontent.append(tmpList)
				
			formatedtable = printtable(cols, tablecontent, mode='sql')
			print formatedtable
			
			if rows == 1:
				print str(rows)+' row in set (%s sec)\n'%t
			else:
				print str(rows)+' rows in set (%s sec)\n'%t
		
    def printErrorResult(self, res):
		pass	

    def showtraceback(self):
        "Over-ride default traceback handling."
        if self.catchErrors:
            if sys.exc_info()[0].__name__ in [
                'SQLError', 
                'SQLSyntaxError',
                'SQLKeyError',
                'SQLForeignKeyError',
            ]:
                print '\a'+sys.exc_info()[0].__name__[3:]+': '+str(sys.exc_info()[1])
            else:
                code.InteractiveConsole.showtraceback(self)
                print "\aBUG: The error described above was not expected and should be considered a bug."
        else:
            raise

if __name__ == '__main__':
    sys.ps1='hirosql>'
    sys.ps2='       >'
    import locale
    locale.setlocale(locale.LC_ALL, '')
    from optparse import OptionParser, OptionGroup
    useage = "usage: %prog [options] database"
    parser = OptionParser(usage=useage, version="%%prog %s.%s"%(__version__[0],__version__[1]))
    parser.add_option("-c", "--create",
                      action="store_true", dest="create", default=False,
                      help="create a database if it doesn't already exist")
    parser.add_option("-d", "--driver",
                      action="store", dest="driver", default='dbm',
                      help="storage mechanism can be dbm [defualt] or csv",
                      type="string")
    parser.add_option("-e", "--raise-exceptions",
                      action="store_false", dest="catchError", default=True,
                      help="exit when any exception occurs")
    (options, args) = parser.parse_args()
    header = """HiroSQL Interactive Prompt\nType SQL or "exit" to quit, "help", "copyright" or "license" for information."""
    c = SQLConsole(args[0], options.catchError, header=header)
    c.interact(header)
